package com.abucloud.logbackdemo.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: 拦截Controller方法的返回值，统一处理返回值
 * @Author party-abu
 * @Date 2021/12/27 16:47
 */
@RestControllerAdvice
public class GlobalResultHandler implements ResponseBodyAdvice<Object> {

    private static final Logger log = LoggerFactory.getLogger(GlobalResultHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 是否执行 beforeBodyWrite方法
     * true：执行 false：不执行
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 在选择HttpMessageConverter之后和调用它的 write 方法之前调用
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 遇到字符串时，提前返回处理，
        // 避免使用StringHttpMessageConvert处理使用Resp类型封装字符串后的数据，导致数据处理异常问题
        if (body instanceof String) {
            try {
                return objectMapper.writeValueAsString(Resp.ok(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        // 解决与统一异常处理产生的冲突问题
        if (body instanceof Resp) {
            return body;
        }

        return Resp.ok(body);
    }


}